package com.hdsx.jxcsxm.utile;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.NodeParser;
import com.hdsx.jxcsxm.xtgl.bean.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 占贤银
 * time 2023/3/10 16:53
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public final class MbCacheUtil {

    private static final Map<String, List<?>> cache =
            new ConcurrentHashMap<String, List<?>>();

    public static void put (String key, List<?> list){
        cache.put(key, list);
    }

    public static boolean exists(String key){
        if (cache.containsKey(key)) {
            return true;
        }
        return false;
    }

    public static List<?> get(String key){
        if (cache.containsKey(key)) {
            return cache.get(key);
        }
        return new ArrayList<TreeNode>();
    }

    public static void remove(){
        if (!cache.isEmpty()) {
            cache.clear();
        }
    }

    /**
     * 查询行政区划、管养单位数据
     * @param list
     * @return
     */
    public static List queryCacheTreeData(List<TreeNode> list) {
        ArrayList<Object> nodeList = CollUtil.newArrayList();
        for (int i = 0; i < list.size(); i++) {
            cn.hutool.core.lang.tree.TreeNode treeNode;
            treeNode = new cn.hutool.core.lang.tree.TreeNode();
            Map<String, Object> extra = new HashMap<String, Object>();
            extra.put("state", list.get(i).getState());
            treeNode.setId(list.get(i).getId());
            treeNode.setParentId(list.get(i).getParent());
            treeNode.setName(list.get(i).getText());
            treeNode.setExtra(extra);
            nodeList.add(treeNode);
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("text");
        treeNodeConfig.setDeep(4);
        String parentId = list.get(0).getParent();
        List treeNodes = TreeUtil.build(nodeList, parentId, treeNodeConfig, new NodeParser() {
            @Override
            public void parse(Object obj, Tree tree) {
                if (obj instanceof cn.hutool.core.lang.tree.TreeNode) {
                    cn.hutool.core.lang.tree.TreeNode treeNode = (cn.hutool.core.lang.tree.TreeNode) obj;
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setName(treeNode.getName());
                    tree.putExtra("state", treeNode.getExtra().get("state"));
                }
            }
        });
        return treeNodes;
    }
}
